package com.hdu.h_health.ui;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.hdu.h_health.Adapter.MyConsultAdapter;
import com.hdu.h_health.R;
import com.hdu.h_health.common.BaseActivity;
import com.hdu.h_health.model.UserModel;
import com.hdu.h_health.model.i.UpdateCacheListener;
import com.hdu.h_health.utils.CommonUtils;
import com.hdu.h_health.widget.DividerItemDecoration;
import com.hdu.h_health.widget.NavigationView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
import cn.bmob.v3.exception.BmobException;

/**
 * 我的咨询列表
 * Created by 612 on 2016/3/9.
 */
public class MyConsultActivity extends BaseActivity {
    private List<BmobIMConversation> bmobIMConversations = new ArrayList<BmobIMConversation>();

    public SwipeRefreshLayout sw_refresh;

    private RecyclerView rc_view;

    private MyConsultAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myconsult);
        adapter = new MyConsultAdapter(this, bmobIMConversations);
        rc_view.setAdapter(adapter);
        query();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rc_view.setLayoutManager(manager);
        rc_view.addItemDecoration(new DividerItemDecoration(this, manager.getOrientation()));
        adapter.setOnItemClickListener(new MyConsultAdapter.onItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Bundle bundle = new Bundle();
                BmobIMConversation c = bmobIMConversations.get(position);
                bundle.putSerializable("c", c);
                startActivity(ChatActivity.class, bundle, false);
            }

            @Override
            public void onItemLongClick(View view, final int position) {
                //以下两种方式均可以删除会话
//                BmobIM.getInstance().deleteConversation(adapter.getItem(position).getConversationId());
                BmobIM.getInstance().deleteConversation(bmobIMConversations.get(position));
                adapter.remove(position);
            }
        });

        sw_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                sw_refresh.setRefreshing(true);
                query();//加载数据
                sw_refresh.setRefreshing(false);
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        sw_refresh = (SwipeRefreshLayout) findViewById(R.id.sw_refresh);
        rc_view = (RecyclerView) findViewById(R.id.rc_view);

        navigationView = (NavigationView) findViewById(R.id.navView);
        navigationView.setTv_title("我的咨询");
        navigationView.getIv_left().setImageResource(R.drawable.ic_keyboard_arrow_left_white_36dp);
//        navigationView.getIv_right().setImageResource(R.drawable.ic_control_point_white_36dp);
        navigationView.setClickListener(new NavigationView.ClickCallBack() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
//                startActivity(new Intent(getBaseContext(), EditSecretActivity.class));
            }
        });
    }


    /**
     * 查询和更新本地会话
     */
    public void query() {
        bmobIMConversations = BmobIM.getInstance().loadAllConversation();
        adapter.change(bmobIMConversations);
    }


    /**
     * 注册离线消息接收事件，SDk内部实现，勿删
     */
    public void onEventMainThread(final OfflineMessageEvent event) {
        //SDK内部已根据用户id对离线消息进行分组
        Map<String, List<MessageEvent>> map = event.getEventMap();
        Logger.i("离线消息属于" + map.size() + "个用户");
        for (Map.Entry<String, List<MessageEvent>> entry : map.entrySet()) {
            List<MessageEvent> list = entry.getValue();
            UserModel.getInstance().updateUserInfo(list.get(0), new UpdateCacheListener() {
                @Override
                public void done(BmobException e) {
                    //重新刷新列表
//                    bmobIMConversations = BmobIM.getInstance().loadAllConversation();
//                    adapter.notifyDataSetChanged();
                    query();
                }
            });
        }
    }

    /**
     * 注册消息接收事件，SDk内部实现，勿删
     *
     * @param event 1、与用户相关的由开发者自己维护，SDK内部只存储用户信息
     *              2、开发者获取到信息后，可调用SDK内部提供的方法更新会话
     */
    public void onEventMainThread(final MessageEvent event) {
        UserModel.getInstance().updateUserInfo(event, new UpdateCacheListener() {
            @Override
            public void done(BmobException e) {
                //获取本地消息并刷新列表
//                bmobIMConversations = BmobIM.getInstance().loadAllConversation();
//                adapter.notifyDataSetChanged();
                UserModel.getInstance().updateUserInfo(event, new UpdateCacheListener() {
                    @Override
                    public void done(BmobException e) {
                        CommonUtils.showToast(getBaseContext(), "update");
                    }
                });
                query();
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        query();
    }
}
